package com.blink.optimize.algorithm.fifo;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <Description> 先进先出缓存</Description>
 * <ClassName> FIFOCache</ClassName>
 *
 * @Author liuxianzhao
 * @Date 2018年01月09日 10:37
 */
public class FIFOCache {
    private final int cacheMaxSize;

    private final LinkedHashMap<String, Object> cacheData;

    public static FIFOCache create(int cacheMaxSize) {
        return new FIFOCache(cacheMaxSize);
    }

    public Object get(String key) {
        return key == null ? null : cacheData.get(key);
    }

    public Object put(String key, Object o) {
        return key == null ? null : cacheData.put(key, o);
    }

    private FIFOCache(int cacheMaxSize) {
        this.cacheMaxSize = cacheMaxSize;
        cacheData = new LinkedHashMap<String, Object>() {
            @Override
            protected boolean removeEldestEntry(Map.Entry<String, Object> eldest) {
                return size() > cacheMaxSize;
            }
        };
    }

    public int getCacheMaxSize() {
        return cacheMaxSize;
    }

    public LinkedHashMap getCacheData() {
        return cacheData;
    }
}
